using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace Weight.Base.Utility
{
    public class RandomHelper
    {
        /// <summary>
        /// 获取随机数(通过Random获取伪随机数)
        /// </summary>
        /// <param name="valLength">获取随机数的多少位(从右侧开始)</param>
        /// <returns></returns>
        public static  string GetValByRandom(int valLength)
        {
            if (valLength <= 0) valLength = 5;
            Random rand = new Random((int)DateTime.Now.Ticks);
            string rndVal = Convert.ToString( rand.Next());
            string reuslt = string.Empty;
            int len = rndVal.Length;
            if (len >= valLength)
            {
                reuslt = rndVal.Substring(len -valLength,5);
            }
            else
            {
                reuslt = rndVal.PadLeft(valLength,'0');
            }
            return reuslt;
        }

        /// <summary>
        /// 获取随机数(通过RNGCryptoServiceProvider)
        /// </summary>
        /// <param name="valLength">获取随机数的多少位(从右侧开始)</param>
        /// <returns></returns>
        public static  string GetValByRNGCryptoServiceProvider(int valLength)
        {
            byte[] data = new byte[8];
            RNGCryptoServiceProvider rndProvider = new RNGCryptoServiceProvider();
            rndProvider.GetBytes(data);
            string  val =Convert.ToString( Math.Abs( BitConverter.ToInt32(data,0)));
            int len = val.Length;
            string result = string.Empty;
            if(len >=valLength)
            {
                result = val.Substring(len-valLength,valLength);
            }
            else
            {
                result = val.PadLeft(valLength,'0');
            }

            return result;
        }
    }
}


